package cn.aicnn.chatssespringboot.service;

import cn.aicnn.chatssespringboot.model.FileMetrics;
import cn.aicnn.chatssespringboot.model.ProjectMetrics;
import cn.aicnn.chatssespringboot.util.JavaProjectMetricsAnalyzer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Service
public class MetricsService {

    public Map<String, Object> analyzeUploadedZip(MultipartFile file) throws Exception {
        // 1. 保存并解压
        Path tempDir = Files.createTempDirectory("upload_");
        File zipFile = new File(tempDir.toFile(), file.getOriginalFilename());
        file.transferTo(zipFile);
        unzip(zipFile.getAbsolutePath(), tempDir.toFile().getAbsolutePath());

        // 2. 分析 Java 项目
        ProjectMetrics metrics = JavaProjectMetricsAnalyzer.analyzeProject(tempDir.toFile().getAbsolutePath());

        // 3. 获取代码行数前十的文件
        List<FileMetrics> topFiles = new ArrayList<>(metrics.fileMetrics);
        topFiles.sort((a, b) -> b.linesOfCode - a.linesOfCode);
        List<FileMetrics> top10 = topFiles.stream().limit(10).toList();

        // 4. 返回 JSON 格式
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> summaryMap = new HashMap<>();
        summaryMap.put("totalFiles", metrics.fileMetrics.size());
        summaryMap.put("totalLines", metrics.totalLines);
        summaryMap.put("totalComments", metrics.totalCommentLines);
        summaryMap.put("totalComplexity", metrics.totalCyclomaticComplexity);
        summaryMap.put("commentDensity", String.format("%.2f", metrics.getCommentDensity()) + "%");
        summaryMap.put("goodFiles", metrics.goodFilesCount);
        summaryMap.put("averageFiles", metrics.averageFilesCount);
        summaryMap.put("poorFiles", metrics.poorFilesCount);
        summaryMap.put("externalInputs", metrics.externalInputs);
        summaryMap.put("externalOutputs", metrics.externalOutputs);
        summaryMap.put("externalQueries", metrics.externalQueries);
        summaryMap.put("internalLogicalFiles", metrics.internalLogicalFiles);
        summaryMap.put("externalInterfaces", metrics.externalInterfaces);

        result.put("projectSummary", summaryMap);
        result.put("topFiles", top10);
        return result;
    }

    private void unzip(String zipFilePath, String destDir) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry zipEntry;
            while ((zipEntry = zis.getNextEntry()) != null) {
                File destFile = new File(destDir, zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    destFile.mkdirs();
                } else {
                    destFile.getParentFile().mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(destFile)) {
                        byte[] buffer = new byte[4096];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zis.closeEntry();
            }
        }
    }
}
